<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise发送AJAX</title>
</head>
    <button>AJAX</button>

    <script>
        let btn = document.querySelector('button');

        btn.onclick = function(){
            let p = new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open("GET",'https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=3941491&appsecret=TXoD5e8P');
                xhr.responseType = 'json';
                xhr.send();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status < 300){
                            //响应体输出
                            if(xhr.response.errcode){//
                                // console.error(xhr.response.errmsg)
                                reject(xhr.response);
                            }else{
                                // console.log('获取成功');
                                resolve(xhr.response);
                            }
                        }else{
                            //请求失败
                            reject(xhr.status);
                        }
                    }
                }
            })
            //调用 then 方法
            p.then(value => {
                console.log(value.city + value.data[0].wea);
            }, reason =>{
                if(typeof reason === 'object'){
                    console.error('获取失败, 失败信息为' + reason.errmsg);
                }
            })
        }
    </script>
<body>
</body>
</html>